import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import {
    Grid,
    Typography,
    InputLabel,
    FormControl,
    MenuItem,
    FormHelperText,
    Select,
    Tabs,
    Tab,
    Box,
    Divider,
    OutlinedInput,
} from '@material-ui/core';
import { Image, Icon } from 'components/atoms';
import { callGetNewsApi, callPostNewsApi } from 'utils/networking';
import { Hero } from "./components"
import { Genres } from "./components"
import { svg } from "./svg"

import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from "react-router-dom";
import { setPlaysItem } from 'redux/actions/PlaysActions'
import { useLocation } from 'react-router-dom/cjs/react-router-dom.min';

const useStyles = makeStyles(theme => ({
    root: {
        width: "100%",
        padding: "20px",
        background: '#000',
        "& .MuiTabs-indicator": {
            display: "none"
        },
        "& .MuiTab-root": {
            color: "white",
        },
        "& .MuiTab-wrapper": {
            padding: "0 8px",
            borderRadius: "2px",
            fontSize:"20px",
            [theme.breakpoints.up('md')]: {
                fontSize:"28px",
            },
        },
        "& .Mui-selected .MuiTab-wrapper": {
            background: "#E24575",
        },
        "& .MuiSvgIcon-fontSizeSmall ": {
            color: "white",
        },
    },
    title: {
        textAlign: "center",
        fontFamily: "HurmeGeometricSans3-Black",
        fontSize: "56px",
        fontStyle: "normal",
        fontWeight: 700,
        lineHeight: "normal",
        color: "rgba(30, 30, 30, 1)",
        padding: "30px 0",
        [theme.breakpoints.up('md')]: {
            fontSize: "63px",
        },
    },
    typography: {
        fontFamily: "HurmeGeometricSans3-Black",
        fontSize: "40px",
        fontStyle: "normal",
        fontWeight: 700,
        lineHeight: "40px",
        textTransform: "uppercase",
        color: "#7E53F9",
        [theme.breakpoints.up('md')]: {
            fontSize: "80px",
            lineHeight: "85px",
        },
        textAlign: "center",
    },
    typography1: {
        color: "#fff",
    },
    typography2: {
        color: "#000",
        lineHeight: "normal",
        fontSize: "25px",
    },
    typography3: {
        fontSize: "16px",
        lineHeight: "normal",
        color: "#C6C6CA",
        wordBreak: "break-all"
    },
    grid: {
        padding: "10px",
    },
    gridItem: {
        padding: "10px",
    },
    image: {
        height: "80px",
        width: "120px",
        borderRadius: "6px",
        overflow: "hidden",
        [theme.breakpoints.up('sm')]: {
            width: "140px",
            height: "90px",
        },
        [theme.breakpoints.up('md')]: {
            width: "130px",
            height: "90px",
        },
        [theme.breakpoints.up('lg')]: {
            height: "100px",
            width: "160px",
        },
    },
    img: {
        objectFit: "cover",
        verticalAlign: "middle",
    },
    image1: {
        // width: "250px",
        height: "250px",
        borderRadius: "8px",
        overflow: "hidden",
        [theme.breakpoints.up('md')]: {
            height: "250px",
        },
        [theme.breakpoints.up('md')]: {
            height: "200px",
        },
        [theme.breakpoints.up('lg')]: {
            height: "300px",
        },
    },
    img1: {
        objectFit: "cover"
    },
    adImage: {
        marginTop: "30px",
        display: "none",
        borderRadius: "8px",
        overflow: "hidden",
        "& span": {
            verticalAlign: "middle",
        },
        [theme.breakpoints.up('md')]: {
            display: "block",
        },
    },
    adLeft: {
        marginRight: "50px"
    },
    medias: {
        minHeight: "50vh",
        [theme.breakpoints.up('md')]: {
            minHeight: "100vh",
        },
    },
    formControl: {
        minWidth: 120,
        width: "100%",
        color: "white",
        backgroundColor: "white",
        paddingLeft: "10px",
        "& .MuiInput-underline:after": {
            border: "none"
        },
        "& .MuiInput-underline:before": {
            border: "none"
        },
        "& .MuiInput-underline:hover:before": {
            border: "none"
        }
    },
    pagination: {
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        padding: "20px 0",
        "& .MuiPaginationItem-page": {
            backgroundColor: "#232637",
            color: "#FFFFFF",
        },
        "& .Mui-selected": {
            backgroundColor: "#E24575",
        },
        "& .MuiPaginationItem-ellipsis": {
            color: "#FFFFFF",
        },
    },
    sort: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: "start",
        position: "absolute",
        top: "50px",
        right: "10px",
        [theme.breakpoints.up('sm')]: {
            top: "0",
        },
        [theme.breakpoints.up('md')]: {
            right: "20px",
            top: "0",
        },
    },
    ul: {
        position: "absolute",
        top: "40px",
        left: "0",
        listStyle: "none",
        zIndex: 20,
        borderRadius: "0 0 4px 4px",
        overflow: "hidden",
        borderTop: "1px solid rgba(0, 0, 0, 0.10)",
        backgroundColor: "#FFFFFF",
    },
    ul1: {
        top: "100%",
        right: "-100%",
    },
    ulHead: {
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        padding: "10px 20px",
        fontFamily: "HurmeGeometricSans3-Black",
        borderBottom: "1px solid rgba(0, 0, 0, 0.10)",
    },
    ulFoot: {
        display: "flex",
        justifyContent: "start",
        alignItems: "center",
        padding: "10px 30px 20px",
        fontFamily: "HurmeGeometricSans3-Black",
        borderTop: "1px solid rgba(0, 0, 0, 0.10)",
    },
    content: {
        maxHeight: "200px",
        overflowY: "auto",
        overflowX: "hidden",
    },
    li: {
        width: "180px",
        cursor: "pointer",
        padding: "8px 10px",
        "&:hover": {
            backgroundColor: "#EDF5FA",
        },
        fontSize: "14px",
        display: "flex",
        justifyContent: "start",
        alignItems: "center",
        minHeight: "50px",
        [theme.breakpoints.up('md')]: {
            width: "200px",
        },
        [theme.breakpoints.up('lg')]: {
            width: "220px",
        },
    },
    li1: {
        width: "500px",
        padding: "8px 40px",
    },
    i: {
        "& svg": {
            verticalAlign: "middle"
        }
    },
    mark: {
        position: "fixed",
        width: "100%",
        height: "100%",
        zIndex: 10,
        marginTop: "-64px",
    },
    searchInputContainer: {
        background: theme.palette.background.paper,
        padding: theme.spacing(1.5),
        boxShadow: '0 4px 14px 0 rgba(0, 0, 0, 0.11)',
        borderRadius: theme.spacing(0.5),
        width: '180px',
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        '& .MuiOutlinedInput-notchedOutline': {
            border: '0 !important',
        },
        '& .MuiOutlinedInput-adornedEnd': {
            paddingRight: 0,
        },
        '& .MuiOutlinedInput-input': {
            padding: 0,
        },
        [theme.breakpoints.up('md')]: {
            width: "200px",
        },
        [theme.breakpoints.up('lg')]: {
            width: "220px",
        },
    },
    iconButton: {
        position: "relative"
    },
    payListImg: {
        backgroundSize: "100% 100%",
    }
}));



const sortType = ["top_rated", "a_z", "z_a", "most_plays", "rand", "most_reviews"]

function Follow() {

    const classes = useStyles();
    const token = localStorage.getItem('token');
    const selectId = useSelector((state) => state.liveFeed.selectId);
    const [searchKey, setSearchKey] = useState('');
    const [sortValue, setSortValue] = useState(null);
    const [followData, setFollowData] = useState({
        followers: [],
        followings: [],
    });
    const [playlists, setPlaylists] = useState([]);
    const [offset, setOffset] = useState(1);

    const searchBlogs = () => {
        getServerSideProps()
    }
    const dispatch = useDispatch()
    const profileData = useSelector((state) => state.auth.profileData)
    const history = useHistory();
    const location = useLocation();
    
    const [currentTab, setCurrentTab] = useState(location.state);
    const handleTabChange = (event, newValue) => {
        setCurrentTab(newValue);
        setOffset(1)
    };

    function a11yProps(index) {
        return {
            id: `simple-tab-${index}`,
            'aria-controls': `simple-tabpanel-${index}`,
        };
    }

    function TabPanel(props) {
        const { children, value, index, ...other } = props;

        return (
            <div
                role="tabpanel"
                hidden={value !== index}
                id={`simple-tabpanel-${index}`}
                aria-labelledby={`simple-tab-${index}`}
                {...other}
            >
                {(
                    <Box sx={{ pt: { xs: 5, sm: 3 }, pb: 5, pl: { xs: 0, sm: 3 }, pr: { xs: 0, sm: 3 }, }}>
                        {children}
                    </Box>
                )}
            </div>
        );
    }

    useEffect(() => {
        getServerSideProps()
    }, [searchKey, offset, sortValue, selectId])

    const getServerSideProps = async () => {
        // callGetNewsApi(`song/livefeed?search_text=${searchKey}&offset=${offset}&limit=16&sort_key=${sortType[sortValue]}&genre_ids=${selectId.join(",")}`, dispatch, (data) => {
        //     console.log(data);
        //     setLiveFeedData(data);
        // })
        callGetNewsApi(`user/followings_and_followers?user_id=${profileData.id}`, dispatch, (data) => {
            console.log(data);
            setFollowData(data);
        })
    }

    const [liveFeedAdData, setLiveFeedAdData] = useState([]);

    useEffect(() => {
        getServerAdProps()
    }, [])

    const getServerAdProps = async () => {
        callGetNewsApi(`song/livefeed_ad`, dispatch, (data) => {
            console.log(data);
            setLiveFeedAdData(data);
        })
    }
    const getServerPlaylistsProps = async () => {
        if (!profileData || !profileData.id) {
            history.push(`signin`);
            return;
        }
        callGetNewsApi(`song/user_playlists?user_id=${profileData.id}&all=1`, dispatch, (data) => {
            console.log(data);
            setPlaylists(data);
        })
    }

    const handlePagination = (_, value) => {
        console.log(value)
        setOffset(value)
    }

    const [mark, setMark] = useState(false);
    const [sortText, setSortText] = useState("");
    const [choosePlaylist, setChosePlaylist] = useState(null);

    const handleClick = (value, index) => {
        // setAnchorEl(event.currentTarget);
        if (value) {
            setSortValue(index);
            setSortText(value)
            setMark(false)
        } else {
            setMark(true)
        }
    };

    const handleClose = () => {
        setMark(false)
    };

    const handleMarkClose = () => {
        setChosePlaylist(null)
    };

    return (
        <div>
            <div className={classes.mark} style={{ height: mark ? "100%" : "0" }} onClick={handleClose}></div>
            <div className={classes.mark} style={{ height: choosePlaylist !== null ? "100%" : "0" }} onClick={handleMarkClose}></div>
            <Hero setSearchKey={setSearchKey} searchBlogs={searchBlogs} />
            <Grid container className={classes.root}>
                <Grid item xs={12} sm={12} md={3}>
                    <Genres />
                    <div className={classes.adLeft}>
                        {
                            liveFeedAdData?.filter((ele, i) => i < 2).map((item, index) => (<div className={classes.adImage} key={index}>
                                <Image
                                    src={item.image_url}
                                    alt={item.image_url}
                                    srcSet={item.image_url}
                                    lazyProps={{ width: '100%', height: '100%' }}
                                />
                            </div>))
                        }
                    </div>
                </Grid>
                <Grid item xs={12} md={9}>
                    <Box sx={{ width: '100%' }}>
                        <Box sx={{ borderBottom: 1, borderColor: 'divider', mt: 4, position: "relative" }}>
                            <Tabs value={currentTab} onChange={handleTabChange} aria-label="simple tabs example" >
                                <Tab label="Followers" {...a11yProps(0)} />
                                <Tab label="Following" {...a11yProps(1)} />
                            </Tabs>
                            <div className={classes.sort}>
                                <div className={classes.searchInputContainer}>
                                    <FormControl fullWidth variant="outlined">
                                        <OutlinedInput
                                            size="large"
                                            // onChange={event => setSearchKey(event.target.value)}
                                            value={sortText}
                                            placeholder="Sort"
                                            endAdornment={<Icon
                                                fontIconClass="fa fa-times"
                                                size="small"
                                                style={{ opacity: 0.5, cursor: "pointer" }}
                                                onClick={() => (setSortValue(""), setSortText(""))}
                                            />}
                                            onClick={() => handleClick("")}
                                        />
                                    </FormControl>
                                </div>
                                <ul className={classes.ul} style={{ display: mark ? "block" : "none" }}>
                                    {
                                        svg.map((item, index) => <li className={classes.li} onClick={() => handleClick(item.text, index)} key={index} style={{ marginTop: index == 0 ? "8px" : "0" }}>
                                            <i className={classes.i}>
                                                {item.svg}
                                            </i>
                                            {item.text}
                                        </li>)
                                    }
                                </ul>
                            </div>
                        </Box>
                        <TabPanel value={currentTab} index={0}>
                            <div className={classes.medias}>
                                <Grid container>
                                    {
                                        followData?.followers.map((item, index) => (<Grid item xs={6} md={4} lg={3} container className={classes.grid} key={index}>
                                            <Grid item xs={12} >
                                                <div className={classes.image1}>
                                                    <Image
                                                        src={item.user?.avatarURL}
                                                        alt={item.user?.avatarURL}
                                                        srcSet={item.user?.avatarURL}
                                                        lazyProps={{ width: '100%', height: '100%' }}
                                                        className={classes.img1}
                                                    />
                                                </div>
                                            </Grid>
                                            <Grid item xs={12} className={classes.gridItem}>
                                                <Typography className={clsx(classes.typography, classes.typography3)}>{item.user.username}</Typography>
                                                <Typography className={clsx(classes.typography, classes.typography3)}></Typography>
                                            </Grid>
                                        </Grid>))
                                    }
                                </Grid>
                            </div>
                            {/* <div className={classes.pagination}>
                                <Pagination count={liveFeedData?.songs.counts?.total_pages} variant="outlined" shape="rounded" onChange={handlePagination} page={offset} />
                            </div> */}
                        </TabPanel>
                        <TabPanel value={currentTab} index={1}>
                            <div className={classes.medias}>
                                <Grid container>
                                    {
                                        followData?.followings.map((item, index) => (<Grid item xs={6} md={4} lg={3} container className={classes.grid} key={index}>
                                            <Grid item xs={12} >
                                                <div className={classes.image1}>
                                                    <Image
                                                        src={item.followed_user?.avatarURL}
                                                        alt={item.followed_user?.avatarURL}
                                                        srcSet={item.followed_user?.avatarURL}
                                                        lazyProps={{ width: '100%', height: '100%' }}
                                                        className={classes.img1}
                                                    />
                                                </div>
                                            </Grid>
                                            <Grid item xs={12} className={classes.gridItem}>
                                                <Typography className={clsx(classes.typography, classes.typography3)}>{item.followed_user?.username}</Typography>
                                                <Typography className={clsx(classes.typography, classes.typography3)}></Typography>
                                            </Grid>
                                        </Grid>))
                                    }
                                </Grid>
                            </div>
                            {/* <div className={classes.pagination}>
                                <Pagination count={liveFeedData?.episodes.counts?.total_pages} variant="outlined" shape="rounded" onChange={handlePagination} page={offset} />
                            </div> */}
                        </TabPanel>
                    </Box>
                </Grid>
            </Grid>
        </div>
    )
}

Follow.propTypes = {
    /**
     * External classes
     */
    className: PropTypes.string,
};

export default Follow

